import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";

const UseRef = ()=>{
  const divRef = useRef<HTMLDivElement>(null);
  const childRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    console.log('divRef', divRef.current?.innerHTML);
  }, []);

  function getChildInputFocus(){
    childRef.current?.focus();
  }

  return <div ref={divRef}>
    <p>UseRef</p>
    <button onClick={getChildInputFocus}>获取child的input光标</button>
    <Child ref={childRef}></Child>
  </div>
}

const Child = forwardRef((props, childRef) =>{
  const inputRef = useRef<HTMLInputElement>(null);
  useImperativeHandle(childRef, ()=>({
    focus: ()=>inputRef.current?.focus(),
    setActive: ()=>inputRef.current?.setAttribute('class', 'active')
  }))
  return <div>
    <input type="text" ref={inputRef} placeholder="子组件的input框框" />
  </div>
});

export default UseRef;
